<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>调试版本 - 智能对话助手</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .chat-container { max-width: 600px; margin: 0 auto; }
        .messages { height: 400px; border: 1px solid #ddd; padding: 10px; overflow-y: auto; margin-bottom: 10px; }
        .input-group { display: flex; gap: 10px; }
        input { flex: 1; padding: 10px; }
        button { padding: 10px 20px; cursor: pointer; }
        .message { margin: 10px 0; padding: 10px; border-radius: 5px; }
        .user { background: #e3f2fd; text-align: right; }
        .assistant { background: #f5f5f5; }
        .status { margin: 10px 0; font-size: 14px; }
        .debug { background: #fff3cd; padding: 10px; margin: 10px 0; border-radius: 5px; }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>智能对话助手 - 调试版本</h1>
        
        <div class="status">
            连接状态: <span id="status">初始化中...</span>
        </div>
        
        <div class="debug" id="debug">
            调试信息将显示在这里...
        </div>
        
        <div class="messages" id="messages">
            <div class="message assistant">
                <strong>助手:</strong> 你好！我是智能助手，可以帮你查询时间和进行计算。
            </div>
        </div>
        
        <div class="input-group">
            <input type="text" id="messageInput" placeholder="输入消息..." maxlength="500">
            <button id="sendButton">发送</button>
            <button id="clearButton">清除</button>
        </div>
        
        <div style="margin-top: 20px;">
            <h3>快速测试:</h3>
            <button onclick="testMessage('你好')">测试问候</button>
            <button onclick="testMessage('现在北京时间是几点？')">测试时间</button>
            <button onclick="testMessage('计算 10 + 20')">测试计算</button>
        </div>
    </div>

    <script>
        class DebugChatApp {
            constructor() {
                this.sessionId = 'debug-' + Date.now();
                this.debug('初始化聊天应用...');
                
                this.initElements();
                this.bindEvents();
                this.updateStatus('已连接 (HTTP)');
                
                this.debug('初始化完成，会话ID: ' + this.sessionId);
            }
            
            initElements() {
                this.messages = document.getElementById('messages');
                this.messageInput = document.getElementById('messageInput');
                this.sendButton = document.getElementById('sendButton');
                this.clearButton = document.getElementById('clearButton');
                this.statusElement = document.getElementById('status');
                this.debugElement = document.getElementById('debug');
                
                this.debug('DOM元素初始化完成');
            }
            
            bindEvents() {
                this.sendButton.addEventListener('click', () => {
                    this.debug('发送按钮被点击');
                    this.sendMessage();
                });
                
                this.messageInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.debug('回车键被按下');
                        e.preventDefault();
                        this.sendMessage();
                    }
                });
                
                this.clearButton.addEventListener('click', () => {
                    this.debug('清除按钮被点击');
                    this.clearMessages();
                });
                
                this.debug('事件绑定完成');
            }
            
            async sendMessage() {
                const message = this.messageInput.value.trim();
                if (!message) {
                    this.debug('消息为空，跳过发送');
                    return;
                }
                
                this.debug('发送消息: ' + message);
                this.addMessage('用户', message);
                this.messageInput.value = '';
                
                // 禁用发送按钮
                this.sendButton.disabled = true;
                this.sendButton.textContent = '发送中...';
                this.updateStatus('发送中...');
                
                try {
                    const response = await fetch('/api/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            sessionId: this.sessionId,
                            message: message
                        })
                    });
                    
                    this.debug('收到响应，状态: ' + response.status);
                    
                    if (response.ok) {
                        const data = await response.json();
                        this.debug('响应数据: ' + JSON.stringify(data).substring(0, 100) + '...');
                        this.addMessage('助手', data.content);
                        this.updateStatus('已连接 (HTTP)');
                    } else {
                        throw new Error('HTTP ' + response.status);
                    }
                } catch (error) {
                    this.debug('发送失败: ' + error.message);
                    this.addMessage('系统', '发送失败: ' + error.message);
                    this.updateStatus('连接错误');
                } finally {
                    // 重新启用发送按钮
                    this.sendButton.disabled = false;
                    this.sendButton.textContent = '发送';
                }
            }
            
            addMessage(sender, content) {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message ' + (sender === '用户' ? 'user' : 'assistant');
                messageDiv.innerHTML = `<strong>${sender}:</strong> ${content}`;
                
                this.messages.appendChild(messageDiv);
                this.messages.scrollTop = this.messages.scrollHeight;
                
                this.debug('添加消息: ' + sender + ' - ' + content.substring(0, 50) + '...');
            }
            
            clearMessages() {
                const messages = this.messages.querySelectorAll('.message');
                messages.forEach((msg, index) => {
                    if (index > 0) { // 保留第一条欢迎消息
                        msg.remove();
                    }
                });
                this.debug('消息已清除');
            }
            
            updateStatus(status) {
                this.statusElement.textContent = status;
                this.debug('状态更新: ' + status);
            }
            
            debug(message) {
                const timestamp = new Date().toLocaleTimeString();
                console.log('[' + timestamp + '] ' + message);
                
                if (this.debugElement) {
                    this.debugElement.innerHTML = '[' + timestamp + '] ' + message;
                }
            }
        }
        
        // 全局测试函数
        function testMessage(message) {
            if (window.chatApp) {
                window.chatApp.messageInput.value = message;
                window.chatApp.sendMessage();
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            console.log('页面加载完成，初始化调试版聊天应用...');
            try {
                window.chatApp = new DebugChatApp();
                console.log('调试版聊天应用初始化成功');
            } catch (error) {
                console.error('初始化失败:', error);
                alert('初始化失败: ' + error.message);
            }
        });
        
        // 全局错误处理
        window.addEventListener('error', function(e) {
            console.error('全局错误:', e.error);
            if (window.chatApp) {
                window.chatApp.debug('全局错误: ' + e.error.message);
            }
        });
    </script>
</body>
</html>
